package com.tobestronger.gulimall.product.exception;

import com.tobestronger.common.exception.BizCodeEnum;
import com.tobestronger.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
//@ResponseBody
//@ControllerAdvice(basePackages = "com.tobestronger.gulimall.product.controller")
@RestControllerAdvice(basePackages = "com.tobestronger.gulimall.product.controller")
public class GulimallProductExceptionControllerAdvice {

    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception exception){
        log.error(BizCodeEnum.UNKNOW_EXCEPTION.getMsg(),exception);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }


    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleMethodArgumentNotValidException(MethodArgumentNotValidException exception){
        Map map = new HashMap();
        exception.getBindingResult().getFieldErrors()
                .forEach(item->{
                    map.put(item.getField(),item.getDefaultMessage());
                });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(), BizCodeEnum.VAILD_EXCEPTION.getMsg())
                .put("data",map);
    }



}
